package org.example.common.config;

import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.MybatisFlexBootstrap;
import com.mybatisflex.core.datasource.FlexDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class MyBatisFlexConfig {

    private final DataSource primaryDataSource;
    private final DataSource secondaryDataSource;
    private final DataSource chatDataSource;

    public MyBatisFlexConfig(
            @Qualifier("primaryDS") DataSource primaryDataSource,
            @Qualifier("caseDS") DataSource secondaryDataSource,
            @Qualifier("chatDS") DataSource chatDataSource
    ) {
        this.primaryDataSource = primaryDataSource;
        this.secondaryDataSource = secondaryDataSource;
        this.chatDataSource = chatDataSource;
    }

    @Bean
    public FlexDataSource flexDataSource() {
        // 创建动态数据源
        FlexDataSource flexDataSource = FlexGlobalConfig.getDefaultConfig()
                .getDataSource();

        flexDataSource.addDataSource("primaryDS", primaryDataSource);
        flexDataSource.addDataSource("caseDS", secondaryDataSource);
        // 聊天数据源
        flexDataSource.addDataSource("chatDS", chatDataSource);
        return flexDataSource;
    }

    @Bean
    public MybatisFlexBootstrap bootstrap(FlexDataSource flexDataSource) {
        // 初始化MyBatis-Flex
        return new MybatisFlexBootstrap()
                .setDataSource(flexDataSource)
                .start();
    }
}